package rpc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-04-01
 * Time: 16:20
 */
public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("1.95.194.117");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("wangkun");
        connectionFactory.setPassword("200411");
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();

        //2.通信
        Channel channel = connection.createChannel();

        //3.接收请求
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body,"UTF-8");
                System.out.println("接收请求: " +request);
                String response = "响应成功";
                AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("","queue2",props,response.getBytes());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };

        channel.basicConsume("queue1",false,defaultConsumer);
    }
}
